from django.http import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect
from myjango.models import Users, Table, Cars
import math


def hw(request):
    return HttpResponse('<h1 align="center" style="color:red" >你是阵地纽</h1>')


def index(request):
    name = request.GET.get('name')

    # 接收前端变量 keywords
    keywords = request.GET.get('keywords')
    if keywords:
        goods = Table.objects.filter(name__contains=keywords)
    else:
        goods = Table.objects.all()
        # 给前端传递的页码列表 pagelist [1 2 3..]  len() 方法获取列表长度
        # math.ceil() 向上取整
        # 封装函数 range(start, end) 自动生成从start 开始（包含）到end结束（不包含）的列表
        pagelist = range(1, math.ceil(len(goods) / 5) + 1)
        # 接收  前端传递的 页码参数
        page = request.GET.get('page')

        # page = {{goods.uid}}
        # 如果有值 字符串 转化为 整数
        if page:
            page = int(page)
            # 如果无值
        else:
            page = 1
        # 截取数据查询的前五个
        goods = goods[5 * (page - 1):5 * (page)]

    return render(request, "index.html", {"goods": goods, 'pagelist': pagelist})


def login(request):
    if request.POST:
        username = request.POST.get('username')
        userpasswd = request.POST.get('userpasswd')
        result = Users.objects.filter(username=username)
        if result:
            if result[0].userpasswd == userpasswd:
                # return HttpResponse(' 登陆成功 ')
                # return render(request, "index.html")
                # 设置session
                request.session['uid'] = result[0].uid
                return redirect('/index/?name=' + result[0].username)  # 重定向
            else:
                # 账号存在 密码错误
                return render(request, "login.html")
        else:
            # 帐号不存
            # return HttpResponse(' 登陆失败 ')
            return render(request, "register.html")
    return render(request, 'login.html')


def register(request):
    if request.POST:
        username = request.POST.get('username')
        userpassword = request.POST.get('password')
        # 插入数据据库
        # 将用户类 实例化 对象
        # user1 = Users(uid=1,username=username,userpasswd=userpassword)
        ##数据保存
        # user1.save()
        Users.objects.create(uid=None, username=username, userpasswd=userpassword)

    return render(request, "register.html")


def nav(request):
    one = [
        {'亚洲': [
            {'中国': ['1111', '222']},
            {'俄罗斯': ['33', '444']},
            {'日本': ['555', '666']},
            {'菲律宾': ['777', '888']}]
        },

        {'欧洲': ['德国', '英国', '挪威', '瑞典']},

        {'美洲': ['美国', '加拿大', '墨西哥', '尼加拉瓜']},

        {'非洲': ['安哥拉', '贝宁']}
    ]

    return render(request, "nav.html", {'one': one})


def goodinfo(request):

     # 接收前端传递  商品id 参数
    gid = request.GET.get('uid')
    # 接收 详情页面加入购物车传递 商品id POST 请求
    if request.POST:
        if request.session.get('uid', None):
            gid = request.POST.get('gid')
            kid = request.session['uid']
            car = Cars(gid=gid, buy_count=1, uid=kid)
            car.save()
        else:
            return redirect('/login/')
    # 根据参数执行数据库操作 条件值 filter
    goods = Table.objects.filter(uid=gid)
    # 接收 详情页购物车传递 商品id
    # car_gid = request.GET.get('car_gid')
    # if car_gid:
    # 根据参数执行数据库操作 插入数据
    #   Cars.objects.create(cid=None, gid=car_gid, buy_count=1)
    #   goods = Table.objects.filter(uid=car_gid)
    return render(request, "goodinfo.html", {'goods': goods})


def cars(request):
    #先判断 判断是否登录 用request.session对象中是否在键uid的值
    if request.session.get('uid',None):
        # 获取 session 中的uid
        uid = request.session['uid']
        # 数据库操作 查询操作 购物车表
        cars = Cars.objects.filter(uid=uid)
        # 数据库查询结果 cars 【{cid gid buy_count}】
        goods = []
        for item in cars:
            good = Table.objects.filter(uid=item.gid)[0]
            good.buy_count = item.buy_count
            good.allPrice = int(item.buy_count) * float(good.price)
            goods.append(good)
        return render(request, "cars.html", {'goods': goods})
